<template>
    <div class="app-container output">
        <el-row :gutter="24">
            <el-col :span="12">
                <el-card :header="`NTP ${$t('setting')}`">
                    <el-form label-width="140px" style="width:75%;margin:0 auto">
                        <el-form-item :label="$t('system time')">
                            <el-row :gutter="12" style="width: 100%;">
                                <el-col :span="18">
                                    <el-date-picker v-model="time" type="datetime" :placeholder="$t('select_placeholder')"
                                        value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                                        style="width:100%" />
                                </el-col>
                                <el-col :span="6" style="text-align: right;">
                                    <el-button type="primary">{{ $t('Sync to PC') }}</el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item :label="`NTP${$t('sync')}`">
                            <el-row :gutter="12" style="width: 100%;">
                                <el-col :span="18">
                                    <el-input v-model="ntpCfg.server" :placeholder="$t('input_placeholder')"></el-input>
                                </el-col>
                                <el-col :span="6" style="text-align: right;">
                                    <el-switch v-model="ntpCfg.enable" inline-prompt active-text="ON"
                                        inactive-text="OFF"></el-switch>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item :label="$t('time zone')">
                            <el-row :gutter="12" style="width: 100%;">
                                <el-col :span="12">
                                    <el-select v-model="timeZone.timeArea" :placeholder="$t('select_placeholder')"
                                        style="width: 100%;" @change="getTimeCityOptions">
                                        <el-option label="Africa" value="Africa"></el-option>
                                        <el-option label="America" value="America"></el-option>
                                        <el-option label="Antarctica" value="Antarctica"></el-option>
                                        <el-option label="Asia" value="Asia"></el-option>
                                        <el-option label="Atlantic" value="Atlantic"></el-option>
                                        <el-option label="Australia" value="Australia"></el-option>
                                        <el-option label="Europe" value="Europe"></el-option>
                                        <el-option label="Indian" value="Indian"></el-option>
                                        <el-option label="Pacific" value="Pacific"></el-option>
                                    </el-select>
                                </el-col>
                                <el-col :span="12">
                                    <el-select v-model="timeZone.timeCity" :placeholder="$t('select_placeholder')"
                                        style="width: 100%;">
                                        <el-option v-for="item in timeCityOptions" :key="item.value" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item :label="$t('time zone')">
                            <el-row :gutter="12" style="width: 100%;">
                                <el-col :span="12">
                                    <el-select v-model="cron_day" :placeholder="$t('select_placeholder')"
                                        style="width: 100%;">
                                        <el-option :label="$t('never')" value="x"></el-option>
                                        <el-option :label="$t('everyday')" value="*"></el-option>
                                        <el-option :label="$t('monday')" value="1"></el-option>
                                        <el-option :label="$t('tuesday')" value="2"></el-option>
                                        <el-option :label="$t('wednesday')" value="3"></el-option>
                                        <el-option :label="$t('thursday')" value="4"></el-option>
                                        <el-option :label="$t('friday')" value="5"></el-option>
                                        <el-option :label="$t('saturday')" value="6"></el-option>
                                        <el-option :label="$t('sunday')" value="0"></el-option>
                                    </el-select>
                                </el-col>
                                <el-col :span="12">
                                    <el-select v-model="cron_time" :placeholder="$t('select_placeholder')"
                                        style="width: 100%;">
                                        <el-option v-for="item in cronTimeOptions" :key="item.value" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="save">{{ $t('Save') }}</el-button>
                            <el-button type="primary" @click="reboot">{{ $t('Reboot') }}</el-button>
                            <el-button type="primary" @click="reset">{{ $t('Reset default') }}</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <template #header>
                        <span>{{ $t('Config file') }}</span>
                        <span style="color: #666;font-size: 14px;">
                            {{ $t('Export the required configuration file as required') }}
                        </span>
                    </template>
                    <div class="config-file">
                        <div class="item">
                            <div class="label">{{ $t('Default Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.config" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('Layout Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.defLays" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('Push Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.push" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('Record Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.record" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('Port Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.port" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('Password Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.passwd" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('NTP Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.cron" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                        <div class="item">
                            <div class="label">{{ $t('Scene Config') }}</div>
                            <div class="content">
                                <el-switch v-model="upConfig.videoBuffer" inline-prompt active-text="ON"
                                    inactive-text="OFF"></el-switch>
                            </div>
                        </div>
                    </div>
                    <div class="btns" style="margin-bottom: 18px;display:flex;justify-content:center">
                        <el-button type="primary" @click="handleExport">{{ $t('Export') }}</el-button>
                        <el-upload class="upload-demo" :action="upcfgUrl" :show-file-list="false" accept=".zip"
                            style="margin-left:20px;" @success="importSuccess" @error="importError">
                            <el-button type="primary">{{ $t('Import') }}</el-button>
                        </el-upload>
                    </div>
                </el-card>
            </el-col>

            <el-col :span="16">
                <el-card :header="$t('Port Config')" style="margin-top:40px" v-if="showPortConfig">
                    <div style="width:80%;margin:0 auto">
                        <el-row :gutter="24" style="margin:20px 0;text-align:center">
                            <el-col :md="5" :sm="8"></el-col>
                            <el-col :md="3" :sm="6">HTTP</el-col>
                            <el-col :md="3" :sm="6">RTSP</el-col>
                            <el-col :md="3" :sm="6">RTMP</el-col>
                            <el-col :md="3" :sm="6">HTTPTS</el-col>
                            <el-col :md="3" :sm="6">Telnet</el-col>
                            <el-col :md="3" :sm="6">SSH</el-col>
                        </el-row>
                        <el-divider></el-divider>
                        <el-row :gutter="24" style="margin:20px 0;text-align:center">
                            <el-col :md="5" :sm="8" style="line-height:32px;text-align:right">{{ $t('Static port')
                            }}</el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.http[0]" :placeholder="$t('input_placeholder')" disabled
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.rtsp[0]" :placeholder="$t('input_placeholder')" disabled
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.rtmp[0]" :placeholder="$t('input_placeholder')" disabled
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.httpts[0]" :placeholder="$t('input_placeholder')" disabled
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.telnet[0]" :placeholder="$t('input_placeholder')" disabled
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.ssh[0]" :placeholder="$t('input_placeholder')" disabled
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24" style="margin:20px 0;text-align:center">
                            <el-col :md="5" :sm="8" style="line-height:32px;text-align:right">{{ $t('Reserve port')
                            }}</el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.http[1]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.rtsp[1]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.rtmp[1]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.httpts[1]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.telnet[1]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.ssh[1]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                        </el-row>
                        <el-row :gutter="24" style="margin:20px 0;text-align:center">
                            <el-col :md="5" :sm="8" style="line-height:32px;text-align:right">{{ $t('NAT port') }}</el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.http[2]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.rtsp[2]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.rtmp[2]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.httpts[2]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.telnet[2]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                            <el-col :md="3" :sm="6">
                                <el-input-number v-model="portCfg.ssh[2]" :placeholder="$t('input_placeholder')"
                                    :precision="0" :min="0" :controls="false"></el-input-number>
                            </el-col>
                        </el-row>
                        <div class="btns" style="margin-bottom: 15px;display:flex;justify-content:center">
                            <el-button type="primary" @click="savePort">{{ $t('Save') }}</el-button>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card :header="$t('Upgrade')" style="margin-top:40px;height: 350px;">
                    <el-form label-width="140px" style="width: 400px;margin: 30px auto;">
                        <el-form-item :label="$t('App version')">{{ videoBuffer.app }}</el-form-item>
                        <el-form-item :label="$t('SDK version')">{{ videoBuffer.sdk }}</el-form-item>
                        <el-form-item :label="$t('Sys version')">{{ videoBuffer.sys }}</el-form-item>

                        <el-form-item :label="$t('upload packet')">
                            <el-upload class="upload-demo" :action="uploadUrl" :show-file-list="false" accept=".bin"
                                style="margin-right:12px;" @success="uploadSuccess" @error="uploadError" name="uploadFile">
                                <el-button type="primary">{{ $t('Select file') }}</el-button>
                            </el-upload>
                            <el-button type="primary" @click="showVerLog">{{ $t('Version Log') }}</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>



        <el-dialog :title="$t('Version Log')" v-model="verLogDialogShow">
            <div class="verLogBox">
                <div v-for="item in verLog">
                    <div class="title">{{ item.version }}</div>
                    <li class="item" v-for="log in item.logs">{{ log }}</li>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
  
<script setup>
import modal from "@/plugins/modal.js"
import { RPC, RPC2, RPC3 } from "@/api/rpc"
import FUNC from "@/api/func"
import getJson from "@/api/getJson"
import i18n from '@/lang'
import { download, uploadUrl, upcfgUrl } from '@/api/file'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import { onBeforeUnmount } from "vue"
const router = useRouter();
console.log(1231231,router)

watch(()=>{
    return router
},(n,o)=>{
    console.log(6666,n)
})

let hardware = reactive({})
getJson('/config/hardware.json').then(res => {
    Object.assign(hardware, res.data)
    if (hardware.function?.portCtrl) {
        initPort()
    }
})

let time = ref('')
FUNC("getTime", null).then(res => {
    if (res.error == '') {
        time.value = res.result[0]
    }
})
let ntpCfg = reactive({})
getJson("config/ntp.json").then(res => {
    Object.assign(ntpCfg, res.data)
})
let timeZone = reactive({})
let timeCityOptions = ref([])
getJson("timezone/tzselect.json").then(res => {
    Object.assign(timeZone, res.data)
    getTimeCityOptions(timeZone.timeArea)
})
function getTimeCityOptions(timeArea) {
    getJson(`timezone/zoneinfo/${timeArea}/`).then(res => {
        if (res.data.length) {
            timeCityOptions.value = res.data.map(item => {
                return { value: item.name, label: item.name }
            })
        }
    })
}
let cron_time = ref('')
let cron_day = ref('')
FUNC("setCron", null).then(res => {
    if (res.result == null || res.result.split(" ").length != 6) {
        cron_time.value = '0'
        cron_day.value = 'x'
    } else {
        cron_time.value = res.result.split(" ")[1]
        cron_day.value = res.result.split(" ")[4]
    }
});
let cronTimeOptions = ref([])
for (let i = 0; i < 24; i++) {
    cronTimeOptions.value.push({ value: String(i), label: i + ":00" })
}

function save() {
    let p1 = FUNC("setNTP", ntpCfg);
    let p2 = FUNC("setTimeZone", timeZone);
    let p3 = FUNC("setCron", { day: cron_day.value, time: cron_time.value })

    Promise.all([p1, p2, p3]).then(res => {
        modal.msgSuccess(i18n.global.t('Save success'))
    })
}
function reboot() {
    modal.confirm(i18n.global.t('Reboot immediately?')).then((params) => {
        FUNC("reboot");
    })
}
function reset() {
    modal.confirm(i18n.global.t('Reset all config to default and reboot immediately?')).then((params) => {
        FUNC("resetCfg");
    })
}


// 配置文件
const upConfig = reactive({
    config: true,
    defLays: false,
    push: false,
    record: false,
    port: false,
    passwd: false,
    cron: true,
    videoBuffer: true,
})
const zip = new JSZip()
let proList = []
let keys = []
function handleExport() {
    keys = Object.keys(upConfig)
    keys.forEach(key => {
        if (upConfig[key])
            if (key == 'cron') {
                proList.push(download('ntp.json'), download("auto/root.cron"), download("misc/timezone/tzselect.json"))
            } else if (key == 'videoBuffer') {
                proList.push(download('board.json'), download("videoBuffer.json"))
            } else {
                proList.push(download(key + '.json'))
            }
    })

    Promise.all(proList).then(res => {
        console.log(res)
        res.forEach(item => {
            if (item) {
                zip.file(item.name, JSON.stringify(item.res), { binary: true })
            }
        })
        console.log(11111, zip.files)
        if (Object.keys(zip.files).length) {
            zip.generateAsync({ type: 'blob' }).then((blob) => {
                saveAs(blob, 'configs.zip');
            });
        }
    })
}
function importSuccess(res) {
    modal.msgSuccess(i18n.global.t('Import success'))
}
function importError(res) {
    modal.msgError(i18n.global.t('Import failed'))
}


// 端口配置
let portCfg = reactive({})
let showPortConfig = ref(false)
function initPort() {

    getJson("config/port.json").then(res => {
        Object.assign(portCfg, res.data)
        showPortConfig.value = true
        console.log(portCfg)

    })
}
function savePort() {
    RPC3("update", [JSON.stringify(portCfg, null, 2)]).then(res => {
        modal.msgSuccess(i18n.global.t('Save success'))
    })
}

// 系统升级

var videoBuffer = reactive({})
getJson("config/version.json").then(res => {
    Object.assign(videoBuffer, res.data)
})
const verLog = reactive({})
const verLogDialogShow = ref(false)
function showVerLog() {
    getJson('config/verLogs.json').then(res => {
        Object.assign(verLog, res.data)
        verLogDialogShow.value = true
    })
}
function uploadSuccess(res) {
    let flag = res.upload
    if (flag == '0') {
        modal.confirm(`${i18n.global.t('Upload success')}.${i18n.global.t('Reboot immediately?')}`).then(res => {
            FUNC("reboot");
        })
    }
    if (flag == '-1') {
        modal.msgError(i18n.global.t('Upload failed, upgrade package model does not match!'))
    }
    if (flag == '-2') {
        modal.msgError(i18n.global.t('Upload failed, the upgrade package does not match the system version!'))
    }
}
function uploadError() {
    modal.msgError(i18n.global.t('Upload failed'))
}

onBeforeUnmount(()=>{
    
})


</script>
  
<style lang='scss' scoped>
.verLogBox {
    padding: 0 40px 40px;
    max-height: 75vh;
    overflow: auto;

    .title {
        font-size: 24px;
        margin: 15px 0
    }

    .item {
        padding-left: 30px;
        line-height: 30px;
        font-size: 16px;
    }
}

.config-file {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;

    .item {
        width: 25%;
        text-align: center;
        margin: 20px 0;

        .label {
            margin-bottom: 10px;
        }
    }
}
.el-input-number{
    width: 100%;
}
</style>
  